﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentValidation;
using Microhard.Permission.Interface;
using FluentValidation.Results;
using Microhard.Core;

namespace Microhard.Permission.Validator
{
    public class ResouceValidator : AbstractValidator<Microhard.Permission.Models.Resouce>
    {
        public ResouceValidator()
        {
            IResouce ir = IoC.Resolve<IResouce>();
            RuleSet("Insert", () =>
            {
                RuleFor(u => u.Name).NotEmpty().WithMessage(MsgForPermission.NeedResouceName).When(u=>u.ResourceID == Guid.Empty);
                RuleFor(u => u.Name).Length(1, 20).WithMessage(MsgForPermission.MaxLenOfResouceName).When(u => u.ResourceID == Guid.Empty);
                RuleFor(u => u.KeyName).NotEmpty().WithMessage(MsgForPermission.NeedResouceKeyName).When(u => u.ResourceID == Guid.Empty);
                RuleFor(u => u.KeyName).Length(1, 20).WithMessage(MsgForPermission.MaxLenOfResouceKeyName).When(u => u.ResourceID == Guid.Empty);
                RuleFor(u => u.ResourceTypeID).NotEmpty().WithMessage("请选择资源类型").When(u => u.ResourceID == Guid.Empty);
                Custom(u => {
                    if (u.ResourceID == Guid.Empty)
                    {
                        if(ir.IsKeyNameDuplicate(u))
                            return new ValidationFailure("DuplicateKeyName", "KeyName重复");
                    }
                    return null;
                });
                Custom(u =>
                {
                    if (u.ResourceID == Guid.Empty)
                    {
                        if (u.AllowGroupID == Guid.Empty)
                            return new ValidationFailure("needGroup", "请选择适用组");
                    }
                    return null;
                });
            });

            RuleSet("Update", () =>
            {
                RuleFor(u => u.Name).NotEmpty().WithMessage(MsgForPermission.NeedResouceName);
                RuleFor(u => u.Name).Length(1, 20).WithMessage(MsgForPermission.MaxLenOfResouceName);
                RuleFor(u => u.KeyName).NotEmpty().WithMessage(MsgForPermission.NeedResouceKeyName);
                RuleFor(u => u.KeyName).Length(1, 20).WithMessage(MsgForPermission.MaxLenOfResouceKeyName);
                RuleFor(u => u.ResourceTypeID).NotEmpty().WithMessage("请选择资源类型");

                Custom(u =>
                {
                    if (u.AllowGroupID == Guid.Empty)
                        return new ValidationFailure("needGroup", "请选择适用组");
                    return null;
                });
            });

            RuleSet("Delete", () => {
            
            });
        }
    }
}
